import { Module } from 'vuex'
import {
  accountLoginRequest,
  getMenuInfo,
  getUserInfo
} from '@/service/login/login'
import { IAccount } from '@/service/login/type'
import { ILoginState } from './type'
import { IRootState } from '../types'
import LocalCache from '@/utils/cache'
import router from '@/router'
export const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
      LocalCache.setCache('token', token)
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
      LocalCache.setCache('userInfo', userInfo)
    },
    cacheUserMenu(state, menu: any) {
      state.userMenus = menu
      LocalCache.setCache('menu', menu)
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      /**
       * 用户登录 保存token 获取id
       */
      const accountLogin = await accountLoginRequest(payload)
      // console.log(accountLogin.data)

      const { id, token } = accountLogin.data
      commit('changeToken', token)

      /**
       * 获取用户的基本信息
       */
      const userInfo = await getUserInfo(id)
      // console.log('用户的基本信息===', userInfo)
      commit('changeUserInfo', userInfo)

      /**
       * 获取用户的导航info
       */
      const MenuInfo = await getMenuInfo(id)
      // console.log('获取用户的导航info', MenuInfo)
      commit('cacheUserMenu', MenuInfo.data)

      router.push('/main')
    },
    loadLocalLogin({ commit, dispatch }) {
      const token = LocalCache.getCache('token')
      if (token) {
        commit('changeToken', token)
        // 发送初始化的请求(完整的role/department)
        // dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = LocalCache.getCache('userInfo')
      if (userInfo) {
        commit('changeUserInfo', userInfo)
      }
      const userMenus = LocalCache.getCache('menu')
      // console.log('userMenus==getcache', userMenus)

      if (userMenus) {
        commit('cacheUserMenu', userMenus)
      }
    }
  }
}
